package com.java.jvm.bytecode.javassist;
import com.java.jvm.bytecode.service.ResourceService;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;

public class JavassistTests {
    public static void main(String[] args)throws Exception {
        //获取CtClass对象的容器
        ClassPool cp = ClassPool.getDefault();
        //从容器中获取ResourceService的类型对象
        CtClass cc = cp.get("com.java.jvm.bytecode.service.ResourceService");
        //获取类型中的CtMethod对象
        CtMethod m = cc.getDeclaredMethod("handle");
        //在方法前插入代码
        m.insertBefore("{ System.out.println(\"start\"); }");
        //在方法后插入代码
        m.insertAfter("{ System.out.println(\"end\"); }");
        //获取类的字节码对象
        Class c = cc.toClass();
        //输出类的字节码文件(可选)
        cc.writeFile("d:/classes/");
        //基于字节码创建对象实例
        ResourceService rs = (ResourceService)c.newInstance();
        rs.handle();
    }
}
